<!-- 选择课程章节抽屉 -->
<template>
  <el-drawer class="chapter-drawer" v-model="visible">
    <div class="container flex-column">
      <div class="font-weight">
        {{ course.course_name }}
      </div>
      <div class="font-weight">请选择课程目录</div>
      <el-tree
        class="chapter-tree"
        ref="chapterRef"
        node-key="id"
        :data="categoryOptions"
        show-checkbox
        :default-checked-keys="props.course.selectedChecked"
        :default-expand-all="true"
      />
      <footer class="flex-end drawer-footer">
        <div class="confirm-btn flex-center hover" @click="onPublish">发布</div>
      </footer>
    </div>
  </el-drawer>
  <TaskDrawer
    v-if="taskVisible"
    v-model:visible="taskVisible"
    :task-type="1"
    :course="{ ...course, chapterList: categoryList }"
  />
</template>

<script setup>
import { defineModel, ref } from 'vue'
import { getChapterList } from '@/apis/assignment/index'
import TaskDrawer from '@/components/publish-task/TaskDrawer.vue'
import { ElMessage } from 'element-plus'

const visible = defineModel('visible')
const taskVisible = ref(false)
const props = defineProps({
  course: {
    type: Object,
    default: () => {
      return {
        course_id: null,
        course_name: '',
        subjectId: 0,
        selectedChecked: []
      }
    }
  }
})

const chapterRef = ref()
const categoryOptions = ref([])
const categoryList = ref([])

const onPublish = () => {
  let chapterList = chapterRef.value.getCheckedNodes()
  if (!chapterList.length) {
    ElMessage.info('请先选择章节')
    return
  }
  categoryList.value = chapterList
    .filter(item => !item.children)
    .map(item => item.id)
  // visible.value = false
  taskVisible.value = true
}

const changeChapter = tree => {
  for (const i in tree) {
    if (tree[i].children) {
      changeChapter(tree[i].children)
    }
    tree[i].label = tree[i].title
  }
}

//获取所有课程章节
const getChapterListInfo = async () => {
  const res = await getChapterList(props.course.course_id)
  let tree = res.data
  changeChapter(tree)
  categoryOptions.value = tree
}

const initData = () => {
  getChapterListInfo()
}

initData()
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  gap: 12px;
  font-size: @size-big;
  .chapter-tree {
    flex: 1;
    overflow-y: auto;
    font-size: @size-big;
    :deep(.el-tree-node__content) {
      margin-bottom: 6px;
    }
  }
  .drawer-footer {
    width: 100%;
  }
}
</style>

<!-- eslint-disable -->
<style lang="less">
.chapter-drawer {
  .el-drawer__header {
    margin-bottom: unset !important;
  }
  .el-drawer__body {
    padding-top: 0px;
  }
}
</style>
